package com.Education.config;

import cn.hutool.core.bean.BeanUtil;
import com.Education.pojo.User;
import com.Education.server.UserService;
import com.Education.util.JwtUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class DatabaseRealm extends AuthorizingRealm{

    @Autowired
    JwtUtils jwtUtils;

    //private final UserService userService;
    @Autowired
    UserService userService;

//    @Autowired
//    public DatabaseRealm(UserService userService) {
//        this.userService = userService;
//    }

    /*
     * shiro默认supports的是UsernamePasswordToken，而我们现在采用了jwt的方式，所以这里我们自定义一个JwtToken，来完成shiro的supports方法
     */
    @Override
    public boolean supports(AuthenticationToken token) {
        System.out.println("supports");
        return token instanceof JwtToken;
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token)throws AuthenticationException {

        System.out.println("————身份认证方法————");
        JwtToken jwtToken = (JwtToken) token;

        String username = jwtUtils.getClaimByToken((String) jwtToken.getPrincipal()).getSubject();

        System.out.println("doGetAuthorizationInfo=======Jwt-username:"+username);

        User user = userService.getUserByName(username);
        if (user == null) {
            throw new UnknownAccountException("账户不存在");
        }

        AccountProfile profile = new AccountProfile();
        BeanUtil.copyProperties(user, profile);

        return new SimpleAuthenticationInfo(profile, jwtToken.getPrincipal(), getName());



        //======================================================================



        /*
        //不使用jwt的部分
        //获取账号密码
        UsernamePasswordToken t = (UsernamePasswordToken) token;
        System.out.println("t:"+t);
        String userName= token.getPrincipal().toString();
        String password= new String( t.getPassword());
        //获取数据库中的密码
        String passwordInDB = userService.getUserByName(userName).getPassword();

        //如果为空就是账号不存在，如果不相同就是密码错误，但是都抛出AuthenticationException，而不是抛出具体错误原因，免得给破解者提供帮助信息
        if(null==passwordInDB || !passwordInDB.equals(password))
            throw new AuthenticationException();

        System.out.println("passwordInDB:"+passwordInDB);
        //认证信息里存放账号密码, getName() 是当前Realm的继承方法,通常返回当前类名 :databaseRealm
        SimpleAuthenticationInfo a = new SimpleAuthenticationInfo(userName,password,getName());
        return a;
        */

    }
}
